<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Admin\Controller;

use Think\AjaxPage;

/**
 * 优惠券控制器  
 */
class CouponController extends BaseController {

    /**
     * 优惠券
     */
    public function index() {
        $couponMod = M('coupon');
        $count = $couponMod->count();
        $Page = new \Think\Page($count, 10);
        $show = $Page->show();
        $lists = $couponMod->order('add_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('lists', $lists);
        $this->assign('page', $show);
        $this->assign('coupons', C('COUPON_TYPE'));
        $this->display();
    }

    /**
     * 修改优惠券
     */
    public function couponInfo() {
        if (IS_POST) {
            $couponRs = I('post.');
            $couponRs['send_start_time'] = strtotime($couponRs['send_start_time']);
            $couponRs['send_end_time'] = strtotime($couponRs['send_end_time']);
            $couponRs['use_end_time'] = strtotime($couponRs['use_end_time']);
            $couponRs['use_start_time'] = strtotime($couponRs['use_start_time']);
            if ($couponRs['send_start_time'] > $couponRs['send_end_time']) {
                $this->error('发放日期填写有误');
                exit;
            }

            if ($couponRs['use_start_time'] > $couponRs['use_end_time']) {
                $this->error('使用日期填写有误');
                exit;
            }

            if (empty($couponRs['id'])) {
                $couponRs['add_time'] = time();
                $status = M('coupon')->add($couponRs);
            } else {
                $status = M('coupon')->where(array('id' => $couponRs['id']))->save($couponRs);
            }
            if (!$status)
                $this->error('编辑优惠券失败');
            $this->success('编辑优惠券成功', U('Admin/Coupon/index'));
            exit;
        }
        $id = I('get.id');
        if ($id) {
            $couponRs = M('coupon')->where(array('id' => $id))->find();
            $this->assign('coupon', $couponRs);
        } else {
            $rs['send_start_time'] = strtotime("+1 day");
            $rs['send_end_time'] = strtotime("+1 month");
            $rs['use_start_time'] = strtotime("+1 day");
            $rs['use_end_time'] = strtotime("+2 month");
            $this->assign('coupon', $rs);
        }
        $this->display();
    }

    /**
     * 优惠券发放
     */
    public function makeCoupon() {
        $id = I('get.id');
        $type = I('get.type');
        $couponRs = M('coupon')->where(array('id' => $id))->find();
        $remain = $couponRs['createnum'] - $couponRs['send_num'];
        if ($remain <= 0)
            $this->error($couponRs['name'] . '已经发放完了');
        if (!$couponRs)
            $this->error("优惠券类型不存在");
        if ($type != 4)
            $this->error("该优惠券类型不支持发放");
        if (IS_POST) {
            $num = I('post.num');
            if ($num > $remain)
                $this->error($couponRs['name'] . '发放量不够了');
            if (!$num > 0)
                $this->error("发放数量不能小于0");
            $data['cid'] = $id;
            $data['type'] = $type;
            $data['send_time'] = time();
            for ($i = 0; $i < $num; $i++) {
                do {
                    $code = get_rand_str(8, 0, 1);
                    $check_exist = M('coupon_list')->where(array('code' => $code))->find();
                } while ($check_exist);
                $data['code'] = $code;
                M('coupon_list')->add($data);
            }
            M('coupon')->where("id=$id")->setInc('send_num', $num);
            adminLog("发放" . $num . '张' . $couponRs['name']);
            $this->success("发放成功", U('Admin/Coupon/index'));
            exit;
        }
        $this->assign('coupon', $couponRs);
        $this->display();
    }

    /**
     * 获取用户
     */
    public function ajaxGetUser() {
        $where = array();
        I('mobile') ? $where['mobile'] = I('mobile') : false;
//        I('email') ? $where['email'] = I('email') : false;
        $nickname = I('nickname');
        if (!empty($nickname)) {
            $where['nickname'] = array('like', "%$nickname%");
        }
        $usersMod = M('users');
        $count = $usersMod->where($where)->count();
        $Page = new AjaxPage($count, 10);
        foreach ($where as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();
        $userRs = $usersMod->where($where)->order("user_id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $usersLevel= M('user_level')->getField('level_id,level_name', true);
        $this->assign('user_level',$usersLevel);
        $this->assign('userList', $userRs);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 发放优惠券
     */
    public function sendCoupon() {
        $id = I('cid');
        if (IS_POST) {
            $levelId = I('level_id');
            $userId = I('user_id');
            $insert = '';
            $couponRs = M('coupon')->where("id=$id")->find();
            if ($couponRs['createnum'] > 0) {
                $remain = $couponRs['createnum'] - $couponRs['send_num'];
                if ($remain <= 0)
                    $this->error($couponRs['name'] . '已经发放完了');
            }

            if (empty($userId) && $levelId >= 0) {
                if ($levelId == 0) {
                    $user = M('users')->where("is_lock=0")->select();
                } else {
                    $user = M('users')->where("is_lock=0 and level_id=$levelId")->select();
                }
                if ($user) {
                    $sendNum = count($user); //本次发送量
                    if ($couponRs['createnum'] > 0 && $remain < $sendNum) {
                        $this->error($couponRs['name'] . '派发量只剩' . $remain . '张');
                    }
                    foreach ($user as $k => $val) {
                        $userId = $val['user_id'];
                        $time = time();
                        $gap = ($k + 1) == $sendNum ? '' : ',';
                        $insert .= "($id,1,$userId,$time)$gap";
                    }
                }
            } else {
                $sendNum = count($userId);
                if ($couponRs['createnum'] > 0 && $remain < $sendNum) {
                    $this->error($couponRs['name'] . '派发量只剩' . $remain . '张');
                }
                foreach ($userId as $k => $v) {
                    $time = time();
                    $gap = ($k + 1) == $sendNum ? '' : ',';
                    $insert .= "($id,1,$v,$time)$gap";
                }
            }
            $sql = "insert into __PREFIX__coupon_list (`cid`,`type`,`uid`,`send_time`) VALUES $insert";
            M()->execute($sql);
            M('coupon')->where("id=$id")->setInc('send_num', $sendNum);
            adminLog("发放" . $sendNum . '张' . $couponRs['name']);
            $this->success("发放成功");
            exit;
        }
        $level = M('user_level')->select();
        $this->assign('level', $level);
        $this->assign('cid', $id);
        $this->display();
    }

    /**
     * 删除优惠券
     */
    public function delCoupon() {
        $id = I('get.id');
        $status = M('coupon')->where(array('id' => $id))->delete();
        if ($status) {
            M('coupon_list')->where(array('cid' => $id))->delete();
            $this->success("删除成功");
        } else {
            $this->error("删除失败");
        }
    }

    /**
     * 优惠券详细查看
     */
    public function couponList() {
        $id = I('get.id');
        $couponRs = M('coupon')->field('id,type')->where(array('id' => $id))->find();
        if (!$couponRs['id'] > 0)
            $this->error('不存在该类型优惠券');

        $sql = "SELECT count(1) as c FROM __PREFIX__coupon_list  l " .
                "LEFT JOIN __PREFIX__coupon c ON c.id = l.cid " . //联合优惠券表查询名称
                "LEFT JOIN __PREFIX__order o ON o.order_id = l.order_id " . //联合订单表查询订单编号
                "LEFT JOIN __PREFIX__users u ON u.user_id = l.uid WHERE l.cid = " . $id;    //联合用户表去查询用户名

        $count = M()->query($sql);
        $count = $count[0]['c'];
        $Page = new \Think\Page($count, 10);
        $show = $Page->show();

        $sql = "SELECT l.*,c.name,o.order_sn,u.nickname FROM __PREFIX__coupon_list  l " .
                "LEFT JOIN __PREFIX__coupon c ON c.id = l.cid " . //联合优惠券表查询名称
                "LEFT JOIN __PREFIX__order o ON o.order_id = l.order_id " . //联合订单表查询订单编号
                "LEFT JOIN __PREFIX__users u ON u.user_id = l.uid WHERE l.cid = " . $id . //联合用户表去查询用户名
                " limit {$Page->firstRow} , {$Page->listRows}";
        $couponList = M()->query($sql);
        $this->assign('coupon_type', C('COUPON_TYPE'));
        $this->assign('type', $couponRs['type']);
        $this->assign('lists', $couponList);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 删除优惠券
     */
    public function couponListDel() {
        $id = I('get.id');
        if (!$id)
            $this->error("缺少参数值");
        $status = M('coupon_list')->where(array('id' => $id))->delete();
        if (!$status)
            $this->error('删除失败');
        $this->success('删除成功');
    }

}
